<script src="https://res.dcdev.net/dcdev/v1.0.8/assets/third_part/monaco-editor/vs/loader.js"></script>

<div style="padding: 0;" class="dcdev-shadow dcdev-border" id="dcdev_source_container">
    <div id="html_editor" style="width:100%"> </div>
</div>
<script>
    //alert(browser_info.is_mobile)
    if (browser_info.is_mobile) {
        console.log("aaa")
        //alert("aaaa")
        //$('#html_editor').css('height', 568);
        //$('#html_editor').css('width', 1024-320);
        //$('#code_container').css('width', 1024-320);
        $('#html_editor').css('height', '400px');
    } else {
        height = getViewPortHeight();
        select_container_height = $('#select_container').outerHeight(true);
        info_height = $('#info').outerHeight(true);
        function_container_height = $('#function_container').outerHeight(true);
        $('#html_editor').css('height', height - select_container_height - info_height - function_container_height -
            50);
    }
    // 获取浏览器窗口的可视区域的高度
    function getViewPortHeight() {
        return document.documentElement.clientHeight || document.body.clientHeight;
    }
    //alert(browser_info.is_mobile)
</script>
<script>
    {

        //一键除重
        function cleanRepeatScriptAndLinkSrc(do_str, data) {
            var result = do_str;
            var do_str_result = searchScriptAndLinkSrc(do_str);
            var data_result = searchScriptAndLinkSrc(data);
            for (var i = 0; i < data_result.length; i++) {
                for (let j = 0; j < do_str_result.length; j++) {
                    if (data_result[i].src == do_str_result[j].src) {
                        var reg = new RegExp(do_str_result[j].content, "g");
                        result = result.replace(reg, "");
                    }
                }
            }
            return result;
        }
        //搜索所有script标签和link标签
        function searchScriptAndLinkSrc(data) {
            var ScriptReg = /<script.*?(?:>|>)<\/script>/gi;
            var LinkReg = /<link.*?(?:>|\/>)/gi;
            var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
            var hrefReg = /href=[\'\"]?([^\'\"]*)[\'\"]?/i;
            var arr = data.match(ScriptReg);
            var arr2 = [];
            try {
                for (var i = 0; i < arr.length; i++) {
                    var src = arr[i].match(srcReg);
                    arr2.push({
                        src: src[1],
                        content: arr[i]
                    });
                }
                arr = data.match(LinkReg);
                for (var i = 0; i < arr.length; i++) {
                    var href = arr[i].match(hrefReg);
                    arr2.push({
                        src: href[1],
                        content: arr[i]
                    });
                }
            } catch (error) {

            }

            return arr2;
        }
        //匹配用户使用组件信息
        function getComponentUseInfo(data) {

            //var pattern = /(?<=\<\!\-\-).*?(?=start)/g;
            var pattern = new RegExp("(?<=\<\!\-\-).*?(?=start)", "gim")
            var temp = data.match(pattern);
            var ans = [];
            // console.log(temp)
            temp.forEach(element => {

                var temp2 = element.split('/');
                obj = {};
                obj.framework = temp2[0];
                obj.info = temp2[1];
                //判断是否在内部
                try {
                    for (let i = 0; i < ans.length; i++) {
                        var info = getComponentData(obj.framework, obj.info)
                        var this_cp = getComponentCode(info.start, info.end);
                        var info2 = getComponentData(ans[i].framework, ans[i].info);
                        var prsent_cp = getComponentCode(info2.start, info2.end);
                        if (this_cp[0].range.startLineNumber <= prsent_cp[0].range.endLineNumber && this_cp[0]
                            .range
                            .endLineNumber <= prsent_cp[0].range.endLineNumber) {
                            obj.small = true;
                        }
                    }

                    //console.log("this_cp", this_cp)
                    // console.log("prsent_cp", prsent_cp)
                } catch (error) {
                    console.log("第一个")
                }
                ans.push(obj);
            });
            window['ComponentUseInfo'] = ans;
            return ans;

        }

        // 获取中间字符串
        function getMiddleString(source_string, start_tag, end_tag) {
            if (source_string == "" || source_string == null || source_string == undefined) { // "",null,undefined
                return "";
            }
            if (source_string.indexOf(start_tag) < 0) {
                return "";
            }
            sub_start_tag = source_string.substring(source_string.indexOf(start_tag) + start_tag.length, source_string
                .length);
            sub_end_tag = sub_start_tag.substring(0, sub_start_tag.indexOf(end_tag));
            return sub_end_tag;
        }

        // 将前后字符串夹住部分替换为另一字符串
        function replaceMiddleString(replace_source, start_tag, end_tag, replace_string) {
            return replace_source.replace(getMiddleString(replace_source, start_tag, end_tag), replace_string);
        }
    }

    // 编辑器相关函数
    {
        // 插入内容到当前位置
        function insert_to_editor(content) {
            editor.focus()
            var selection = editor.getSelection()
            var range = new monaco.Range(selection.startLineNumber, selection.startColumn, selection.endLineNumber,
                selection.endColumn)
            var id = {
                major: 1,
                minor: 1
            }
            var op = {
                identifier: id,
                range: range,
                text: content,
                forceMoveMarkers: true
            }
            editor.executeEdits('html_editor', [op])
        }

        // 获取当前选中内容
        function get_selected_content() {
            return editor.getModel().getValueInRange(editor.getSelection())
        }

        // 获取搜索范围
        function get_search_keyword(keyword) {
            return editor.getModel().findMatches(keyword)
        }

        // 选中指定范围的内容
        function select_by_range(range) {
            editor.setSelection(range)
        }
        //滚动到底部，并且光标到底部
        function EditorToBottom() {
            //获取行数
            var data = editor.getValue().split('\n')
            //设置滚动
            editor.setScrollTop(editor.getScrollHeight());
            var height = editor.getScrollTop();
            editor.setScrollTop(height - 500);
            //设置选择
            editor.setPosition({
                lineNumber: data.length,
                column: 1
            });
        }
        // 替换当前选中内容（没有选中内容则插入到当前位置）
        function replace_selected_content(text) {
            let selection = this.editor.getSelection()
            let range = new monaco.Range(selection.startLineNumber, selection.startColumn, selection.endLineNumber,
                selection.endColumn)
            let id = {
                major: 1,
                minor: 1
            }
            let op = {
                identifier: id,
                range: range,
                text: text,
                forceMoveMarkers: true
            }
            this.editor.executeEdits(this.root, [op])
            this.editor.focus()
        }

        // 删除当前选中内容
        function remove_selected_content() {
            let selection = this.editor.getSelection()
            let range = new monaco.Range(selection.startLineNumber, selection.startColumn, selection.endLineNumber,
                selection.endColumn)
            let id = {
                major: 1,
                minor: 1
            }
            let op = {
                identifier: id,
                range: range,
                text: "",
                forceMoveMarkers: true
            }
            this.editor.executeEdits(this.root, [op])
            this.editor.focus()
        }

        // 当前选中是否包含某些内容
        function has_text_in_selection(text) {
            return get_selected_content().indexOf(text) > -1 ? true : false;
        }
    }

    // 获取样式内容
    function get_style_content() {
        if (has_text_in_selection("style=") || has_text_in_selection("style =")) {
            // 获得标签内容
            var tag_content = get_selected_content()
            var reg = /\<(.+?)\>/g;
            var tag_array = tag_content.match(reg);
            tag_array.forEach(element => {
                if (element.indexOf("style=") > 0 || element.indexOf("style =") > 0) {
                    const reg = /\'(.*?)\'/;
                    const reg2 = /\"(.*?)\"/;
                    if (element.indexOf("'") > 0) {
                        // console.log(reg.exec(element)[1])
                    } else {
                        // console.log(reg2.exec(element)[1])
                    }
                }
            });
        }
    }
    var checknode = [];
    var checktitle = [];
    var checktype = "";
    var body_node_list = null;
    var body_compost_func = null;
    //样式表格
    function show_style_form() {
        loadJs(`https://res.dcdev.net/dcdev/v1.0.8/part/body_part.js`, function () {
            // 节点处理
            body_node_list = _dc_body_part.node_list;
            body_node_list_html = "";
            body_compost_func_html = "";
            for (const key in body_node_list) {
                if (body_node_list.hasOwnProperty(key)) {
                    const element = body_node_list[key];
                    body_node_list_html +=
                        `<input type="radio" lay-filter="body_attribute" name="body_attribute" value="${key}" title="${key}">`
                    // `<button onclick="get_html_tag_name('body_node_list_attribute','${key}')" style="margin-right:5px;margin-bottom:5px;">${key}</button>`
                }
            }
            $("#body_node_list").html(body_node_list_html)

            // 组合功能
            body_compost_func = _dc_body_part.compost_func;
            for (const key in body_compost_func) {
                if (body_compost_func.hasOwnProperty(key)) {
                    const element = body_compost_func[key];
                    body_compost_func_html +=
                        `<input type="radio" lay-filter="body_compost" name="body_compost" value="${key}" title="${key}">`
                    // `<button onclick="get_html_tag_name('body_node_list_attribute','${key}')" style="margin-right:5px;margin-bottom:5px;">${key}</button>`
                }
            }
            $("#body_compost_func").html(body_compost_func_html)
            // layui.form.render()
        })
        $("#style_container").html(`<div id="body_node_list" class="layui-form"
                                                style="display: -webkit-inline-box;width:100%">
                                            </div>
                                            <div class="layui-form body_node_list_attribute" style="display: none;"><table class="layui-table">
                                                    <thead>
                                                        <tr>
                                                            <th>节点类型</th>
                                                            <th>默认值</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody id="body_node_list_attribute">
                                                    </tbody>
                                                </table>
                                                </div>
                                                <div style="width: 100%;text-align: right;">
                                                    <label
                                                        style="color: #1296db;font-size: 12px;float: left;">先选中多个标签之后操作</label><br>
                                                    <label style="width: 100%;" class="dcdev-title">节点style</label>
                                                    <input id="line_style"
                                                        style="width: 100%;height:44px;margin-bottom: 10px" />
                                                    <button id="body_node_list_submit">确定</button>
                                                </div>`)
        layui.use(['element', 'form', "table", "layer", "colorpicker"], function () {
            form = layui.form;
            table = layui.table;
            element = layui.element;
            colorpicker = layui.colorpicker;
            form.render();
            table.render();
            element.render();
            form.on("radio(body_compost)", function (obj) {})
            form.on("radio(body_attribute)", function (obj) {
                checktype = obj.value;
                $("#line_style").val("")
                var attributedata = body_node_list[obj.value]['default'][0];
                var body_node_list_attribute_html = "";
                for (k in attributedata) {
                    body_node_list_attribute_html += `<tr><td data-node="${k}" data-key="${obj.value}" onmouseover="showNodeTips(this)">
                    <input type="checkbox" lay-filter="body_attribute_node" name="body_attribute_node" lay-skin="primary"  value="${attributedata[k]}" title="${k}">
                    </td>
                    <td><div style="font-size:13px">${attributedata[k]}</div></td>
                    </tr>`
                }
                $("#body_node_list_attribute").html(body_node_list_attribute_html)
                form.render()
                $(".body_node_list_attribute").show();
            })
            form.on("checkbox(body_attribute_node)", function (obj) {
                checknode = [];
                checktitle = [];
                var linestyle_html = "";
                $("input:checkbox[name='body_attribute_node']:checked").each(function (i) {
                    checknode.push($(this).val());
                    checktitle.push($(this).attr('title'));
                    linestyle_html += `${$(this).attr('title')}="${$(this).val()}" `
                });
                $("#line_style").val(linestyle_html)
            })
        });
        $("#body_node_list_submit").click(function () {
            var attributedata = body_node_list[checktype]['default'][0];
            var checknode_html = `<${checktype} `;
            if ($("#line_style").val() != "") {
                checknode_html += ` ${$("#line_style").val()} `
            } else {
                for (var i = 0; i < checknode.length; i++) {
                    checknode_html += ` ${checktitle[i]}='${checknode[i]}'`
                }
            }
            if (checktype == "input" || checktype == "img") {
                checknode_html += ` />`
            } else if (checktype == "select") {
                checknode_html += `<option value ="option1">option1</option>
            <option value ="option2">option2</option>
            <option value ="option3">option3</option>
            ></${checktype}>`
            } else {
                checknode_html += `>${checktype}</${checktype}>`
            }
            replace_selected_content(checknode_html)
        })
    }

    // 获取预览区域的dom
    function get_preview_dom() {
        return $($("#preview_mobile")[0].contentWindow.document.body).children()[0];
    }
    // get_style_content();

    var update_preview_timeout;

    // 获取浏览器窗口的可视区域的高度
    function getViewPortHeight() {
        return document.documentElement.clientHeight || document.body.clientHeight;
    }

    // 初始化编辑器
    var editor = null;
    require.config({
        paths: {
            'vs': 'https://res.dcdev.net/dcdev/v1.0.8/assets/third_part/monaco-editor/vs'
        },
        'vs/nls': {
            'availableLanguages': {
                '*': 'zh-cn'
            }
        }
    });
    require(['vs/editor/editor.main'], function () {
        //创建编辑器
        editor = monaco.editor.create(
            document.getElementById('html_editor'), {
                value: [''].join('\n'),
                language: 'html',
                theme: 'vs-dark'
            });
        //隐藏加载
        $("#_progress_").fadeOut(500);
        $(".mask").fadeOut('slow');
        // 载入组件内容
        {
            var url;
            // 设置页面
            if (is_setting_page) {
                // 读取页面内容
                url =
                    `https://res.dcdev.net/project/${project_info.pid}/pages/${project_info.page_id}.html?v=${new Date().getTime()}`;
                $.ajax({
                    url: url, //json文件位置
                    type: "get", //请求方式为get
                    success: function (res) {
                        content = `               
<script src="https://libs.baidu.com/jquery/2.0.0/jquery.min.js"><\/script>
<script src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"><\/script>
<script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"><\/script>
<script src="https://res.dcdev.net/dcdev/v1.0.8/assets/js/utility.js"><\/script>
<script src="https://res.dcdev.net/dcdev/v1.0.8/assets/js/login.js" id="initClass" authorize_mode="normal"><\/script>
`
                        // 替换掉保存时插入的内容，特别是jquery,否则预览会报错
                        content = res.replace(content, "");
                        editor.setValue(content);
                        EditorToBottom();
                    },
                    error: function (res) {
                        // 页面内容不存在，则读取项目配置
                        url =
                            `https://res.dcdev.net/project/${project_info.pid}/config/${md5(project_info.pid+project_info.project_owner_uid)}.json?v=${new Date().getTime()}`;
                        $.ajax({
                            url: url, //json文件位置
                            type: "get", //请求方式为get
                            success: function (res) {
                                var html = `
${res.page_config_action_head_code}
${res.page_config_action_body_code}
${res.page_config_action_script_code}
`
                                editor.setValue(html);
                                EditorToBottom();
                            },
                            error: function (res) {
                                // 页面内容不存在，项目配置也不存在，则使用默认
                                var html = `
<head>
	<meta charset="UTF-8">
	<meta content="yes" name="apple-mobile-web-app-capable">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<\/head>
<body>



<\/body>
<script src="https://libs.baidu.com/jquery/2.0.0/jquery.min.js"><\/script>
<script>

<\/script>
`
                                editor.setValue(html);
                                EditorToBottom();

                            }
                        })
                    }
                })
            }
            // 设置组件
            else {
                //debugger;
                url = `https://res.dcdev.net/component/${url_params.id}.html?v=${new Date().getTime()}`;
                if (url_params && url_params.id) {
                    $.ajax({
                        url: url, //json文件位置
                        type: "get", //请求方式为get
                        success: function (res) {
                            debugger;
                            editor.setValue(res);
                            EditorToBottom();
                        }
                    })
                }
            }
        }
        //监听编辑框内容变化
        editor.onDidChangeModelContent((e) => {
            // 延时更新实时预览
            clearTimeout(update_preview_timeout);
            update_preview_timeout = setTimeout(() => {
                var js_code = ''
                if (window['dev_mode']) {
                    js_code = `
                            <script>
                        function get_mouse_position_dom(e){
                            var dom = e.path[0];
                            $(parent.window['CURRENT_DOM']).css('border','');
                            $(dom).css('border','solid');
                            parent.window['CURRENT_DOM'] =dom;
                            localStorage.setItem('CURRENT_DOM', $(dom).html());
                        }
                    <\/script>`

                } else {
                    js_code = '<script>function get_mouse_position_dom(e){}<\/script>';
                }

                var html = `
<style>
    html {
        height: 100%;
    }

    body {
        margin: 0px;
        padding: 0px;
        overflow: hidden;
        height: 100%;
    }
<\/style>
<script src="https://libs.baidu.com/jquery/2.0.0/jquery.min.js"><\/script>

${js_code}
<div onmouseover='get_mouse_position_dom(event);' id="body_container" style="height: 100%;overflow: auto;position: inherit;">
${editor.getValue()} 
<\/div>
`               
                
                var iframeHtml = $(`#preview_mobile`).get(0);
                // //iframeHtml.contentWindow.location.reload();
                iframeHtml.contentWindow.document.write(html); // 动态写入返回页面到iframe
                iframeHtml.contentWindow.document.close();
                 iframeHtml.onload = function(){
                //     //iframeHtml.contentWindow.document.body.innerHTML = "";
                //     
                    iframeHtml.contentDocument.onclick = function () {
                        if (window['dev_mode']) {
                            //定位到相关代码
                            var reg = new RegExp(' style=""', "g")
                            var reg2 = new RegExp(' style="border: solid;"', "g")
                            var reg3 = new RegExp(' border: solid;', "g")
                            
                            var temp = domToStirng(window['CURRENT_DOM']).replace(reg,"").replace(reg2,"").replace(reg3,"");
                            console.log(temp);
                            var data = editor.getModel().findMatches(temp.substr(1));
                            //赋值给开发者工具弹窗
                            $('#dev_content').val(temp);
                            $('#dev_num').html(data.length);
                            window['CURRENT_DOM_CLICK'] = window['CURRENT_DOM']
                            console.log(data);
                            if (data.length <= 0) {
                                layer.msg('找不到该元素的代码相关位置，可能是即时渲染的。');
                                return;
                            }
                            console.log()
                            //选中相关代码
                            window['CURRENT_DOM_LENGTH'] =   data.length;
                            window['CURRENT_DOM_INDEX'] =   0;
                            window['CURRENT_DOM_DATA']  =data;
                            select_by_range(data[window['CURRENT_DOM_INDEX']].range);
                            var tips="";
                            data.forEach(element => {
                             tips = tips+ element.range.startLineNumber+ ','
                               
                            });
                            layer.msg('您要修改的代码块在' + tips + '行。');
                            editor.revealLineInCenter(data[0].range.startLineNumber);
                            //免费移动到相应位置
                        }

                    };
                 };
                //iframeHtml.contentWindow.document.body.innerHTML = html;
                //$(`#preview_mobile`).attr("srcdoc", html);
            }, 300);
            //绑定点击事件
            // var iframe = document.getElementById('preview_mobile');
            // console.log(iframe)
            // iframe.onload = function () {

            // }
        });
    });

    // 快捷键保存
    document.onkeydown = function (event) {
        var e = event || window.event || arguments.callee.caller.arguments[0];
        // ctl+s || cmd+s (osx / window)
        if (browser_info.is_osx) {
            if (e.metaKey && e.keyCode == 83) {
                // 设置页面
                if (is_setting_page) {
                    save_page_code();
                }
                // 设置组件
                else {
                    save_component_code();
                }
                event.returnValue = false;
            }
        } else {
            if (e.ctrlKey && e.keyCode == 83) {
                // 设置页面
                if (is_setting_page) {
                    save_page_code();
                }
                // 设置组件
                else {
                    save_component_code();
                }
                event.returnValue = false;
            }
        }
    }
    //DOM转字符串
    function domToStirng(dom){
            var dom2 = dom.cloneNode(true);
            var div= document.createElement("div");
            div.appendChild(dom2);
            return div.innerHTML
    }
    //搜索代码块，重要！放入code模块
    function getComponentCode(data_start, data_end) {
        var arr = [];
        var starts = editor.getModel().findMatches(data_start);
        var ends = editor.getModel().findMatches(data_end);
        //注释数量不匹配 错误！
        if (starts.length != ends.length) {
            return null;
        }

        for (let i = 0; i < starts.length; i++) {
            var start = starts[i];
            var end = ends[i];
            var data = editor.getModel().getValueInRange(new monaco.Range(start.range.startLineNumber, start.range
                .startColumn, end.range.endLineNumber, end.range.endColumn));
            arr.push({
                content: data,
                range: new monaco.Range(start.range.startLineNumber, start.range.startColumn, end.range
                    .endLineNumber, end.range.endColumn)
            })
        }

        return arr;
    }
</script>